package com.google.code.irouter.portal.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.code.irouter.model.Model;
import com.google.code.irouter.model.Solution;
import com.google.code.irouter.portal.client.rpc.solution.SolutionResult;
import com.google.code.irouter.portal.client.rpc.solution.SolutionService;
import com.google.code.irouter.utils.CacheUtil;
import com.google.code.irouter.utils.ModelUtil;
import com.google.code.irouter.utils.TextUtil;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class SolutionServiceImpl extends RemoteServiceServlet implements SolutionService {

	private static final long serialVersionUID = -9027622480633184521L;

	@Override
	public List<SolutionResult> load() throws IllegalArgumentException {
		List<SolutionResult> solutionResultList = new ArrayList<SolutionResult>();
		try {
			Map<String, Object> filter = new HashMap<String, Object>();
			filter.put("owner", getThreadLocalRequest().getUserPrincipal().getName());
			List<Model> objectList = ModelUtil.select(Solution.class, filter);
			for(Object object : objectList){
				Solution solution = (Solution) object;
				SolutionResult solutionResult = new SolutionResult();
				solutionResult.setId(String.valueOf(solution.getKey().getId()));
				solutionResult.setName(solution.getName());
				solutionResultList.add(solutionResult);
			}
		} catch (Exception exception) {
			// TODO
		}
		return solutionResultList;
	}

	@Override
	public boolean select(String id) throws IllegalArgumentException {
		try {
			Key key = KeyFactory.createKey(Solution.class.getSimpleName(), Long.valueOf(id));
			List<Model> records = ModelUtil.select(Solution.class, key);
			if(records.size() == 0)
				return false;
			String cacheKey = getKey(
					getThreadLocalRequest().getUserPrincipal().getName()
			);
			CacheUtil.put(cacheKey, id);
		} catch (Exception exception) {
			// TODO
			return false;
		}
		return true;
	}

	private static String getKey(String user) {
		return TextUtil.contact(
					true, 
					Solution.class.getName(),
					user
				);
	}

	@Override
	public SolutionResult get() throws IllegalArgumentException {
		SolutionResult result = null;
		Map<String, Object> query = new HashMap<String, Object>();
		query.put(
				"owner",
				getThreadLocalRequest().getUserPrincipal().getName()
		);
		List<Model> modelList = ModelUtil.select(Solution.class, query);
		if(modelList.size() > 0) {
			Solution solution = (Solution) modelList.get(0);
			result = new SolutionResult();
			result.setId(String.valueOf(solution.getKey().getId()));
			result.setName(solution.getName());
		}
		return result;
	}
}
